﻿using Bing.Maps;
using GSISW8.BingMapsServiceReference;
using GSISW8.Common;
using GSISW8.GSISServiceReference;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.ServiceModel;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

namespace GSISW8
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : LayoutAwarePage
    {
        public MainPage()
        {
            this.InitializeComponent();
        }

        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        private async void AFMCheck_Click(object sender, RoutedEventArgs e)
        {

            if(!ValidateAFM(txtAFM.Text.Trim()))
            {
                MessageDialog md = new MessageDialog("Το ΑΦΜ που δώσατε είναι λάθος. Διορθώστε και προσπαθήστε ξανά");
                await md.ShowAsync();
                txtAFM.Focus(Windows.UI.Xaml.FocusState.Keyboard);
                return;
            }

            ShowProgress();

            RgWsBasStoixEpitRtUser details = null;
            try
            {
                RgWsBasStoixNClient cl = new RgWsBasStoixNClient();
                var result = await cl.rgWsBasStoixEpitAsync(new rgWsBasStoixEpitRequest(txtAFM.Text.Trim(), new RgWsBasStoixEpitRtUser(), 5, new GenWsErrorRtUser()));
                details = result.pBasStoixEpitRec_out;
            }
            catch (Exception)
            {
                HideProgress();
                MessageDialog md = new MessageDialog("Δεν ήταν δυνατή η σύνδεση με την υπηρεσία, πιθανότητα δεν είστε συνδεδεμένοι στο Internet. Συνδεθείτε και δοκιμάστε ξανά");
                md.ShowAsync();
                return;   
            }
            
            LayoutRoot.DataContext = details;

            GeocodeServiceClient cl2 = new GeocodeServiceClient(new BasicHttpBinding(),
                new EndpointAddress("http://dev.virtualearth.net/webservices/v1/geocodeservice/geocodeservice.svc"));
            GeocodeResponse geocodeResponse = null;
            try
            {
                geocodeResponse =
                    await cl2.GeocodeAsync(new GeocodeRequest()
                   {
                       Credentials = new Credentials() { ApplicationId = "AmDM6hZxut0vtCKkeKzUgzqEQCFcCrDR_6igkn0__6_c9K158vDfkhwcgj97359l" },
                       Address = new Address()
                       {
                           CountryRegion = "Greece",
                           AddressLine = details.postalAddress + " " + details.postalAddressNo,
                           PostalTown = details.parDescription,
                           PostalCode = details.postalZipCode
                       }
                   });
            }
            catch (Exception)
            {
                xartis.Visibility = Visibility.Collapsed;
                return;
            }
            finally
            {
                HideProgress();
            }
            if (geocodeResponse.Results.Count > 0 && geocodeResponse.Results[0].Locations.Count > 0)
            {
                xartis.Visibility = Visibility.Visible;
                Bing.Maps.Location loc = new Bing.Maps.Location(geocodeResponse.Results[0].Locations[0].Latitude, geocodeResponse.Results[0].Locations[0].Longitude);
                Pushpin pu = new Pushpin();
                MapLayer.SetPosition(pu, loc);
                xartis.Children.Add(pu);
                xartis.Center = loc;
                xartis.SetView(loc,15.0f);
            }
        }

        private void ShowProgress()
        {
            progress.Visibility = Visibility.Visible;
            progress.IsIndeterminate = true;
        }

        private void HideProgress()
        {
            progress.Visibility = Visibility.Collapsed;
            progress.IsIndeterminate = false;
        }

        internal static bool ValidateAFM(string AFM)
        {
            long ypoloipo, sinolo;
            int i, j;

            if (AFM.Length != 9)
                return false;

            for (i = 2, j = 7, sinolo = 0; j >= 0; j--, i += i)
                sinolo += i * (AFM[j] - '0');
            ypoloipo = sinolo % 11;

            return (ypoloipo == 10) ? AFM[8] == '0' : (AFM[8] - '0') == ypoloipo;
        }
    }
}
